<!DOCTYPE html>
<html>
    <head>
        <title>Python_crawl_news</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <script src="https://unpkg.com/htmx.org@1.9.6"></script>
        <div class="container">
            <h1>新闻爬取工具</h1>
            
            <!-- 爬取按钮 -->
            <button 
                hx-get="/crawl_news" 
                hx-target="#news-container" 
                hx-indicator="#loading"
                hx-on::click="this.disabled=true"
                hx-on::after-request="this.disabled=false"
                class="crawl-btn"
            >
                开始爬取新闻
            </button>

            <!-- 加载指示器 -->
            <div id="loading" class="loading" style="display: none;">
                正在爬取新闻，请稍候...
            </div>

            <!-- 错误信息展示区 -->
            <div id="error-message" class="error" style="color: red; margin: 10px 0;"></div>

            <!-- 新闻列表展示区 -->
            <div id="news-container" class="news-list">
                <!-- 新闻内容将通过HTMX动态加载到这里 -->
            </div>
        </div>

        <style>
            .container {
                max-width: 800px;
                margin: 0 auto;
                padding: 20px;
                font-family: Arial, sans-serif;
            }
            .crawl-btn {
                padding: 10px 20px;
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 16px;
            }
            .crawl-btn:disabled {
                background-color: #cccccc;
                cursor: not-allowed;
            }
            .loading {
                margin: 15px 0;
                padding: 10px;
                background-color: #f0f0f0;
                border-radius: 4px;
            }
            .news-list {
                margin-top: 20px;
                line-height: 1.6;
            }
            .news-item {
                margin: 10px 0;
                padding: 10px;
                border-bottom: 1px solid #eee;
            }
        </style>

        <script>
            document.addEventListener('htmx:afterRequest', function(event) {
            const container = document.getElementById('news-container');
            const errorDiv = document.getElementById('error-message');
            errorDiv.textContent = '';
            container.innerHTML = ''; // 先清空容器，避免显示原始JSON
            
            try {
                // 1. 获取响应数据（优先用responseJSON，失败则手动解析responseText）
                let response = event.detail.xhr.responseJSON;
                if (!response) {
                    // 手动解析响应文本（处理responseJSON为undefined的情况）
                    response = JSON.parse(event.detail.xhr.responseText);
                }
                
                // 2. 检查response是否有效
                if (!response) {
                    throw new Error("响应数据格式错误，无法解析");
                }
                
                // 3. 处理正常响应
                if (response.success) {
                    let newsHtml = '<h2>爬取结果</h2>';
                    // 额外检查news是否为数组，避免遍历非数组导致的错误
                    if (Array.isArray(response.news)) {
                        response.news.forEach((item, index) => {
                            newsHtml += `<div class="news-item">${index + 1}. ${item}</div>`;
                        });
                    } else {
                        newsHtml += '<p>未获取到有效新闻列表</p>';
                    }
                    container.innerHTML = newsHtml;
                } else {
                    errorDiv.textContent = `错误: ${response.message || '未知错误'}`;
                }
                
            } catch (e) {
                // 4. 捕获所有解析/运行时错误
                console.error("处理响应失败:", e);
                errorDiv.textContent = `数据处理失败: ${e.message}`;
            }
            });
        </script>
    </body>
</html>